package edu.zut.main.thread;

public class ThreadMoney {
    public static void main(String[] args) {

        Account account = new Account(100);

        DrawMoneyThread boy = new DrawMoneyThread(account,60);
        DrawMoneyThread girl = new DrawMoneyThread(account,30);

        new Thread(boy,"boy").start();
        new Thread(girl,"girl").start();
    }
}
//模仿boy，girl同时取钱
class DrawMoneyThread implements Runnable{
    private Account account;
    private int drawMoney;//取款额

    public DrawMoneyThread(Account account, int drawMoney) {
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public void run(){
        synchronized (account) {
            //取钱过程

            if (account.getNum() >= drawMoney) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                account.setNum(account.getNum() - drawMoney);
                System.out.println(Thread.currentThread().getName() + "取完钱后 剩下：" + account.getNum());
            } else {
                System.out.println(Thread.currentThread().getName() + "余额不足");
            }
        }
    }
}
class Account{
    private int num;

    public Account(int num) {
        this.num = num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public synchronized int getNum() {
        return num;
    }
}
